<template>
  <el-dialog
      v-model="dialogVisible"
      title="批量导出软件著作权"
      width="80%"
      :before-close="handleClose"
  >
    <div class="export-content">
      <!-- 字段选择区域 -->
      <div class="field-selection">
        <p class="section-label">字段选择区域 <el-icon><QuestionFilled /></el-icon></p>
        <div class="field-tags">
          <el-tag
              v-for="field in fields"
              :key="field.key"
              class="field-tag"
              :effect="field.selected ? 'light' : 'plain'"
              @click="toggleField(field)"
          >
            {{ field.label }}
          </el-tag>
        </div>
      </div>

      <!-- 表格预览区域 -->
      <el-table
          :data="tableData"          style="width: 100%"
          :border="true"
          class="export-table"
      >
        <el-table-column
            v-for="field in selectedFields"
            :key="field.key"
            :prop="field.key"
            :label="field.label"
            :min-width="field.width || 120"
        />
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleExport">下载Excel</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { exportCopyright } from "@/api/result/copyright.js"

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  software: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue'])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const fields = ref([
  { key: 'nickName', label: '用户昵称', selected: true },  { key: 'title', label: '著作权名称', selected: true, width: 200 },
  { key: 'certificateNo', label: '证书号', selected: true },
  { key: 'authorRank', label: '本人排名', selected: true },
  { key: 'finishTime', label: '开发完成时间', selected: true },
  { key: 'puttime', label: '获得时间', selected: true },
  { key: 'registerNo', label: '登记号', selected: true },
  { key: 'copyrightType', label: '著作权类型', selected: true },
  { key: 'copyrightOwner', label: '著作权人', selected: true },
  { key: 'description', label: '备注信息', selected: true },
  { key: 'syncStatus', label: '成果同步', selected: true },
  { key: 'created', label: '创建时间', selected: true },
  { key: 'updated', label: '更新时间', selected: true },
  { key: 'authorInfo', label: '作者信息', selected: true, width: 200 }


])

const selectedFields = computed(() => fields.value.filter(f => f.selected))

const tableData = ref([])

watch(() => props.software, (newSoftware) => {
  console.log('原始数据:', newSoftware)
  tableData.value = newSoftware.map(software => ({
    ...software,
    finishTime: formatDate(software.finishTime),
    puttime: formatDate(software.puttime),
    created: formatDate(software.created),
    updated: formatDate(software.updated),
    authorInfo: formatAuthorInfo(software.authorInfo)
  }));
  console.log('处理后的数据:', tableData.value);
}, { immediate: true })

const toggleField = (field) => {
  field.selected = !field.selected
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleCancel = () => {
  dialogVisible.value = false
  ElMessage.info('已取消导出')
}

const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  if (isNaN(d.getTime())) return '';
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};

const formatAuthorInfo = (authorInfo) => {
  if (!authorInfo || !Array.isArray(authorInfo)) {
    return ''; // 或者返回其它默认值
  }
  return authorInfo.map(author => author.name || '').join(', ');
};

const handleExport = async () => {
  const selectedFields = fields.value.filter(f => f.selected);
  if (selectedFields.length === 0) {
    ElMessage.warning('请至少选择一个导出字段');
    return;
  }

  // 准备导出的数据
  const selectedFieldKeys = selectedFields.map(field => field.key);
  const exportData = tableData.value.map(software => {
    const filteredSoftware = {};
    selectedFieldKeys.forEach(key => {
      filteredSoftware[key] = software[key]; // 直接使用键值
    });
    return filteredSoftware;
  });

  try {
    const response = await exportCopyright({
      fields: selectedFields,
      data: exportData
    });


      const blob = response
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'exported_software_copyrights.xlsx';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      ElMessage.success('导出成功');

  } catch (error) {
    ElMessage.error('导出失败: ' + error.message);
  }

  dialogVisible.value = false; // 关闭对话框
};

</script>


<style scoped>
.export-content {
  padding: 20px 0;
}

.field-selection {
  margin-bottom: 24px;
}

.section-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.field-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.field-tag {
  cursor: pointer;
  user-select: none;
}

.field-tag:hover {
  border-color: #409eff;
}

.export-table {
  margin-top: 20px;
  border-radius: 4px;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  border-bottom: 1px solid #dcdfe6;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #dcdfe6;
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
